/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:马星俊
 */

import {post, tree} from '@/utils/request';
import {ApiResult} from '@/utils/data';
import {eachTree, exportExcel} from '@/utils/utils';
import config from '@/config';
import {SysDeptModel} from './data';
import {DndNodeModel} from "@/global";
import React from "react";

/** 获取系统机构接口基地址 */
const getUrl = (url: string) => config.apiBaseUrl + '/sys/dept' + url;

/** 系统机构接口服务 */
const service = {
  /** 新建系统机构 */
  async insert(data: SysDeptModel): Promise<ApiResult> {
    return post(getUrl('/insert'), data);
  },

  /** 修改系统机构 */
  async update(data: SysDeptModel): Promise<ApiResult> {
    return post(getUrl('/update'), data);
  },

  /** 保存系统机构 */
  async save(created: boolean, oldRecord: any, newRecord: any): Promise<ApiResult> {
    return created ? service.insert(newRecord) : service.update(newRecord)
  },

  /** 修改系统机构状态 */
  async updateStatus(ids: string, status: boolean | number): Promise<ApiResult> {
    return post(getUrl('/updateStatus'), {ids, status});
  },

  /** 根据主键字符串删除系统机构 */
  async delete(ids: string): Promise<ApiResult> {
    return post(getUrl('/delete'), {ids});
  },

  /** 根据主键查询单个系统机构 */
  async selectById(id: string): Promise<ApiResult<SysDeptModel>> {
    return post(getUrl('/selectById'), {id});
  },

  /** 查询系统机构列表 */
  async selectList(data: any) {
    return post(getUrl('/selectList'), data);
  },

  /** 获取机构Tree列表 */
  async selectTreeList(data?: any) {
    const r = await tree(getUrl('/selectList'), data, (p: SysDeptModel) => {
      p.key = p.id;
      p.value = p.id;
      p.title = p.name;
    });
    eachTree(r.data, obj => {
      if (obj.children) {
        obj.icon = (<i className='fa fa-folder'/>);
      } else {
        obj.icon = (<i className='fa fa-file'/>);
      }
    })
    return r;
  },

  /** 保存节点拖拽数据 */
  async updateDnd(data: DndNodeModel[]) {
    return post(getUrl('/updateDnd'), data);
  },

  /** 导出系统机构列表 */
  export(data: any) {
    exportExcel(getUrl('/export'), data);
  },
}

export default service;
